package net.wang.concurrency.test.lock;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ----------ReentrantLock    和   Synchronized
 * 可重入性    Y                      Y
 * 锁的实现  代码实现Lock接口         JVM控制
 * 性能区别  较好                    JDK5后优化后较好
 * <p>
 * 功能区别  手动加锁解锁
 * 灵活
 * 可以指定是公平所还是非公平锁
 */
@Slf4j
public class LockExample2 {


    public static int clientTotal = 5000; //请求的总数
    public static int threadTotal = 200; //最大并发数
    public static int count = 0;

    private static final Lock lock = new ReentrantLock();

    @Test
    public void threadSafeTest() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info("exception : {}", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count = {}", count);
    }

    /**
     * 多个线程执行到add方法
     */
    public void add() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}
